package club.xyes.zkh.ecommerce.web.api.controller;

import club.xyes.zkh.ecommerce.commons.dto.DatetimeRange;
import club.xyes.zkh.ecommerce.commons.entity.Shop;
import club.xyes.zkh.ecommerce.commons.entity.TransactionLog;
import club.xyes.zkh.ecommerce.commons.exception.BadRequestException;
import club.xyes.zkh.ecommerce.commons.exception.InternalServerErrorException;
import club.xyes.zkh.ecommerce.commons.exception.ResourceNotFoundException;
import club.xyes.zkh.ecommerce.commons.properties.WebsiteConfigurationProperties;
import club.xyes.zkh.ecommerce.commons.util.DateTimeUtil;
import club.xyes.zkh.ecommerce.commons.util.EntityImagePathUtils;
import club.xyes.zkh.ecommerce.commons.vo.GeneralResult;
import club.xyes.zkh.ecommerce.service.ShopService;
import club.xyes.zkh.ecommerce.service.TransactionLogService;
import club.xyes.zkh.ecommerce.web.controller.BaseController;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Create by 郭文梁 2019/4/19 0019 18:21
 * TransactionLogController
 * 交易记录相关数据访问控制器
 *
 * @author 郭文梁
 * @data 2019/4/19 0019
 */
@Api("交易记录相关接口")
@RestController
@RequestMapping("/api/transaction")
public class TransactionLogController extends BaseController<TransactionLog> {
    private static final int DEFAULT_PAGE = 1;
    private static final int DEFAULT_ROWS = 10;
    private final TransactionLogService service;
    private final WebsiteConfigurationProperties websiteConfigurationProperties;
    private final ShopService shopService;

    @Autowired
    public TransactionLogController(TransactionLogService service,
                                    WebsiteConfigurationProperties websiteConfigurationProperties,
                                    ShopService shopService) {
        super(service);
        this.service = service;
        this.websiteConfigurationProperties = websiteConfigurationProperties;
        this.shopService = shopService;
    }

    /**
     * 查找当前用户的订单
     *
     * @param page 页码
     * @param rows 每页大小
     * @return GR
     */
    @ApiOperation("当前用户的交易记录")
    @GetMapping("/mine")
    public GeneralResult<PageInfo<TransactionLog>> mine(Integer page, Integer rows) {
        page = page == null ? DEFAULT_PAGE : page;
        rows = rows == null ? DEFAULT_ROWS : rows;
        Integer userId = getRequiredUserInfo().getUserId();
        PageInfo<TransactionLog> logs = service.findByUserId(userId, page, rows);
        String serverPrefix = websiteConfigurationProperties.getStaticServerPrefix();
        String filePath = websiteConfigurationProperties.getShopLogoPath();
        logs.setList(logs.getList().stream()
                .peek(v -> EntityImagePathUtils.prettyLogoPath(v.getShop(), serverPrefix, filePath))
                .collect(Collectors.toList()));
        return GeneralResult.ok(logs);
    }

    /**
     * 商家交易概览信息
     *
     * @param shopId 商铺ID
     * @return GR
     */
    @ApiOperation("商家交易概览信息")
    @GetMapping("/shop/{shopId}/overview/{type}")
    public GeneralResult<Map<String, Object>> shopOverview(@PathVariable("shopId") Integer shopId,
                                                           @PathVariable("type") String type) {
        Shop shop = shopService.getRequired(shopId);
        DatetimeRange range;
        switch (type) {
            case "today":
                range = DateTimeUtil.range(0, 1);
                break;
            case "yesterday":
                range = DateTimeUtil.range(-1, 1);
                break;
            case "week":
                range = DateTimeUtil.range(-6, 7);
                break;
            case "month":
                range = DateTimeUtil.range(-29, 30);
                break;
            default:
                return GeneralResult.badRequest("Unknown overview type:" + type);
        }
        Map<String, Object> res = service.overview(shop, range);
        return GeneralResult.ok(res);
    }

    /**
     * 根据ShopId查询交易记录
     *
     * @param shopId ShopId
     * @param page   页码
     * @param rows   每页大小
     * @return GR
     * @
     */
    @ApiOperation("根据ShopId查询交易记录")
    @GetMapping("/shop/{shopId}")
    public GeneralResult<?> findByShopId(@PathVariable("shopId") Integer shopId,
                                         Integer amount,
                                         Integer page, Integer rows) {
        page = page == null ? DEFAULT_PAGE : page;
        rows = rows == null ? DEFAULT_ROWS : rows;
        PageInfo<TransactionLog> logs;
        if (amount == null) {
            logs = service.findByShopId(shopId, page, rows);
        } else {
            logs = service.searchByAmount(shopId, amount, page, rows);
        }
        return GeneralResult.ok(logs);
    }

    /**
     * 通过消费金额查询店铺的消费记录
     *
     * @param shopId 商铺ID
     * @param amount 消费金额 单位：分
     * @return GR
     */
    @GetMapping("/shop/{shopId}/search")
    @ApiOperation("通过消费金额查询店铺的消费记录")
    public GeneralResult<List<TransactionLog>> searchByAmount(@PathVariable("shopId") Integer shopId,
                                                              @RequestParam("amount") Integer amount) {
        List<TransactionLog> logs = service.searchByAmount(shopId, amount);
        return GeneralResult.ok(logs);
    }

    /**
     * 删除交易记录
     *
     * @param id ID
     * @return GR
     */
    @DeleteMapping("/{id}")
    @ApiOperation("删除交易记录")
    public GeneralResult<TransactionLog> delete(@PathVariable("id") Integer id) {
        Shop shop = currentShop();
        TransactionLog log = service.getRequired(id);
        if (!Objects.equals(shop.getId(), log.getShopId())) {
            throw new BadRequestException("您没有权限操作该数据");
        }
        if (service.deleteById(log.getId())) {
            return GeneralResult.ok(log);
        } else {
            throw new InternalServerErrorException("Unable to delete TransactionLog for id " + log.getId());
        }
    }

    /**
     * 当前商铺
     *
     * @return 商铺
     */
    private Shop currentShop() {
        return currentShop(shopService);
    }

}
